<template>
  <div class="page-container">
    <div class="page-card-container flex-row" v-global-loading="loading">
      <div style="width: 20%">
        <a-tree
          v-if="orgArr && orgArr.length"
          v-model:selectedKeys="treeInfo.selectedKeys"
          default-expand-all
          :tree-data="orgArr"
          @select="treeSelect"
        >
          <template #title="item">
            {{ item.title }}
          </template>
        </a-tree>
      </div>
      <div class="flex1">
        <a-form class="mb-10" :model="pageSet" layout="inline">
          <a-form-item label="关键词">
            <a-input
              style="width: 250px"
              v-model:value="pageSet.searchValue"
              placeholder="请输入姓名、账号、手机号"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              allow-clear
              v-model:value="pageSet.searchStatus"
              style="width: 186px"
            >
              <a-select-option
                :value="Number(item.code)"
                :key="index"
                v-for="(item, index) in getDicValue('common_status')"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <div class="commonBtn-primary" @click="loadPagination(true)">
              搜索
            </div>
          </a-form-item>
          <a-form-item>
            <div class="commonBtn-primary" @click="reset">重置</div>
          </a-form-item>
          <a-form-item>
            <div class="commonBtn-primary" @click="goHandle(1)">新增</div>
          </a-form-item>
        </a-form>
        <a-table
          size="small"
          row-key="id"
          :loading="tableLoading"
          :dataSource="tableData"
          :columns="columns"
          bordered
          :pagination="false"
        >
          <template #bodyCell="{text, record, index, column}">
            <div
              class="flex-row-xy-center c-primaryColor fs-12"
              v-if="column.title == '操作'"
            >
              <!-- v-btn-permission="'people:details'" -->
              <span class="pointer mr-10" @click="goHandle(2, record)"
                >详情</span
              >

              <!-- v-btn-permission="'people:role'" -->
              <span class="pointer mr-10" @click="goHandle(4, record)"
                >角色授权</span
              >
              <!-- v-btn-permission="'people:password'" -->
              <span class="pointer mr-10" @click="goHandle(5, record)"
                >重置密码</span
              >
              <!-- <span class="pointer" @click="goHandle(3,record,index)">删除</span> -->
            </div>
          </template>
        </a-table>
        <Pagination
          class="mt-10"
          :page-set="pageSet"
          :load-pagination="loadPagination"
        ></Pagination>
      </div>

      <a-drawer
        width="50%"
        v-model:open="showModal"
        :title="handleTitle"
        :destroyOnClose="true"
        @close="showModalCon(1)"
      >
        <a-form ref="formRef" :model="form" :label-col="{span: 8}">
          <a-row :gutter="20">
            <a-col :span="12">
              <a-form-item
                label="账号"
                name="account"
                :rules="[
                  {required: true, message: '请填写账号', trigger: 'change'}
                ]"
              >
                <a-input
                  v-model:value="form.account"
                  placeholder="请填写账号"
                  :disabled="handleType !== 1"
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12" v-if="handleType === 1">
              <a-form-item
                label="密码"
                name="password"
                :rules="[
                  {required: true, message: '请填写密码', trigger: 'change'}
                ]"
              >
                <a-input-password
                  v-model:value="form.password"
                  placeholder="请填写密码"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12" v-if="handleType === 1">
              <a-form-item
                label="确认密码"
                name="confirm"
                :rules="[
                  {required: true, message: '请确认密码', trigger: 'change'}
                ]"
              >
                <a-input-password
                  v-model:value="form.confirm"
                  placeholder="请确认密码"
                />
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item
                label="姓名"
                name="name"
                :rules="[
                  {required: true, message: '请填写账号', trigger: 'change'}
                ]"
              >
                <a-input v-model:value="form.name" placeholder="请填写账号" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="性别" name="sex">
                <a-select
                  allow-clear
                  v-model:value="form.sex"
                  style="width: 100%"
                  placeholder="请选择性别"
                >
                  <a-select-option
                    :value="Number(item.code)"
                    :key="index"
                    v-for="(item, index) in getDicValue('sex')"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="手机"
                name="phone"
                :rules="[
                  {required: true, message: '请填写手机', trigger: 'change'}
                ]"
              >
                <a-input v-model:value="form.phone" placeholder="请填写手机" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="状态"
                name="status"
                :rules="[
                  {required: true, message: '请选择状态', trigger: 'change'}
                ]"
              >
                <a-select
                  allow-clear
                  v-model:value="form.status"
                  placeholder="请选择状态"
                >
                  <a-select-option
                    v-for="(item, index) in getDicValue('common_status')"
                    :value="Number(item.code)"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="昵称" name="nickName">
                <a-input
                  v-model:value="form.nickName"
                  placeholder="请填写昵称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="生日" name="birthday">
                <a-date-picker
                  style="width: 100%"
                  v-model:value="form.birthday"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="邮箱" name="email">
                <a-input v-model:value="form.email" placeholder="请填写邮箱" />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item
                  label="电话"
                  name="tel"
                  :rules="[{ required: true, message: '请填写电话', trigger: 'change' }]"
              >
                <a-input v-model:value="form.tel" placeholder="请填写电话"/>
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item
                label="所属机构"
                name="orgId"
                :rules="[
                  {required: true, message: '请选择机构', trigger: 'change'}
                ]"
              >
                <a-tree-select
                  v-model:value="form.orgId"
                  style="width: 100%"
                  :dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
                  placeholder="请选择机构"
                  show-search
                  tree-node-filter-prop="title"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="orgArr"
                >
                  <template #title="item">
                    <span @click="changeOrg(item.title)">{{ item.title }}</span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <!-- <a-form-item label="职位" name="posIdList">
                <a-select
                  allow-clear
                  mode="multiple"
                  v-model:value="form.posIdList"
                  placeholder="请选择职位"
                >
                  <a-select-option
                    v-for="(item, index) in posArr"
                    :value="item.id"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item> -->
              <a-form-item
                label="角色"
                name="roleIdList"
                v-if="handleType !== 1"
              >
                <a-select
                  allow-clear
                  mode="multiple"
                  v-model:value="form.roleIdList"
                  disabled
                >
                  <a-select-option
                    v-for="(item, index) in tableData1"
                    :value="item.id"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select></a-form-item
              >
            </a-col>
          </a-row>
          <!-- <a-divider>附属机构</a-divider>
          <a-button style="margin-bottom: 10px;" @click="addorg">
            <PlusOutlined style="padding-right: 5px" />增加附属机构
          </a-button>
          <a-row :gutter="20">
            <a-col :span="12">
              <a-form-item label="附属机构" v-for="(text, index) in extIds">
                <a-tree-select v-model:value="text.orgId" style="width: 85%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择附属机构" allow-clear
                  tree-default-expand-all :tree-data="orgArr">
                  <template #title="item">
                    <span @click="changeOrg1(item, index)">{{ item.title }}</span>
                  </template>
                </a-tree-select>
                <delete-outlined style="margin-left: 5px;font-size: 18px;cursor: pointer;" @click="deleData(index)" />
              </a-form-item>
            </a-col>
          </a-row> -->
        </a-form>
        <template #footer>
          <div class="flex-row-xy-center">
            <a-button style="margin-right: 20px" @click="showModalCon(1)"
              >取消</a-button
            >
            <a-button type="primary" @click="showModalCon(2)">提交</a-button>
          </div>
        </template>
      </a-drawer>
      <a-modal
        width="500px"
        ::zIndex="700"
        v-if="showModal4"
        v-model:open="showModal4"
        title="角色授权"
        @ok="checkedOk"
      >
        <a-form ref="formRef" :model="authorization">
          <a-form-item label="角色" name="roleIdList">
            <a-select
              allow-clear
              mode="multiple"
              v-model:value="authorization.roleIdList"
              placeholder="请选择角色"
            >
              <a-select-option
                v-for="(item, index) in tableData1"
                :value="item.id"
                :key="index"
              >
                {{ item.name }}
              </a-select-option>
            </a-select></a-form-item
          >
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {
  userPage,
  userAdd,
  userDelete,
  userDetail,
  userUpdate,
  orgTree,
  posList,
  ownRole,
  grantRole,
  resetPwd
} from "@/api/configCenter/auth/people";
import {rolePage} from "@/api/configCenter/auth/role";
import useAppStore from "@/store/app";
import {Modal} from "ant-design-vue";
import Pagination from "@/components/pagination/Pagination.vue";
import {getDicValue} from "@/utils/common";
import {message} from "ant-design-vue";
import {notification} from "ant-design-vue";
// import { exportExcel } from "@/utils/exportFile";

//全局加载状态
const loading = ref(false);
const pageSet: any = ref({
  pageNo: 1,
  pageSize: 20,
  total: 0,
  "sysEmpParam.orgId": null
});
const pageSet2 = ref({
  pageNo: 1,
  pageSize: 999,
  total: 0
});
const tableData: any = ref([]); //表格数据
const tableData1: any = ref([]);
const tableLoading = ref(false);
const form: any = ref({});
const formRef = ref();
const showModal4 = ref(false);
const treeInfo = ref({
  selectedKeys: []
});
const reset = () => {
  pageSet.value = {
    pageNo: 1,
    pageSize: 20,
    total: 0,
    "sysEmpParam.orgId": null
  };
  loadPagination(true);
};
//获取表格数据
const loadPagination = (reset = false) => {
  tableLoading.value = true;
  if (reset) {
    tableData.value = [];
    pageSet.value.pageNo = 1;
  }
  userPage(pageSet.value)
    .then((res) => {
      tableLoading.value = false;
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
    })
    .catch((err) => {
      tableLoading.value = false;
    });
};

loadPagination();
function loadPagination1() {
  rolePage(pageSet2.value).then((res) => {
    tableData1.value = res.data.rows;
  });
}
loadPagination1();
//角色授权
function checkedOk() {
  grantRole(authorization.value).then((res) => {
    message.success("授权成功");
    showModal4.value = false;
  });
}
const treeSelect = (selectedKeys, e) => {
  if (e.selected) {
    pageSet.value["sysEmpParam.orgId"] = e.node.id;
  } else {
    pageSet.value["sysEmpParam.orgId"] = null;
  }
  loadPagination(true);
};

//机构列表
const orgArr = ref([]);
const loadOrgTree = () => {
  orgTree().then((res) => {
    orgArr.value = res.data;
  });
};
loadOrgTree();

//职位列表
const posArr: any = ref([]);
const getPosList = () => {
  posList().then((res) => {
    posArr.value = res.data;
  });
};
getPosList();
const authorization: any = ref({});
const showModal = ref(false);
const handleTitle = ref<string>();
const handleType = ref<number>();
const goHandle = (type: number, info?: any, index?: number) => {
  handleType.value = type;
  form.value = {};
  if (type === 1) {
    handleTitle.value = "新增";
    extIds.value = [{}];
    showModal.value = true;
    return;
  }
  if (type === 2) {
    handleTitle.value = "详情";
    useAppStore.loading = true;
    userDetail({id: info.id}).then((res) => {
      form.value = res.data;
      if (form.value.sex == 0) {
        form.value.sex = null;
      }
      ownRole({id: info.id}).then((res) => {
        form.value.roleIdList = res.data;
      });
      // form.value.orgId = res.data.sysEmpInfo.orgId
      // form.value.posIdList = res.data.sysEmpInfo.positions.map(item => item.posId)
      // extIds.value = res.data.sysEmpInfo.extOrgPos
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }
  if (type === 3) {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗",
      onOk() {
        useAppStore.loading = true;
        userDelete({id: info.id}).then((res) => {
          tableData.value.splice(index, 1);
          useAppStore.loading = false;
        });
      }
    });
    return;
  }
  if (type === 4) {
    showModal4.value = true;
    authorization.value.sysUserId = info.id;
    ownRole({id: info.id}).then((res) => {
      authorization.value.roleIdList = res.data;
    });
  }
  if (type == 5) {
    loading.value = true;
    resetPwd({id: info.id})
      .then((res) => {
        loading.value = false;
        notification["success"]({
          message: "密码重置成功!",
          description: "新密码为Dk1q2w3e$"
        });
      })
      .catch((err) => {
        loading.value = false;
      });
  }
};
//附属机构集合
const extIds: any = ref([]);
const addorg = () => {
  extIds.value.push({});
};
const deleData = (index) => {
  extIds.value.splice(index, 1);
};
function changeOrg1(data, index) {
  extIds.value[index].orgName = data.title;
}
const showModalCon = (type) => {
  if (type == 1) {
    formRef.value.clearValidate();
    showModal.value = false;
  } else if (type == 2) {
    if (handleType.value === 1) {
      if (form.value.account.length < 5) {
        message.error("用户名不能小于5位！");
        return;
      }
      formRef.value.validate().then((res) => {
        useAppStore.loading = true;
        form.value.sysEmpParam = {
          orgId: form.value.orgId,
          orgName: form.value.orgName,
          posIdList: form.value.posIdList,
          extIds: extIds.value
        };
        if (!form.value.sex) {
          form.value.sex = 3;
        }
        if (!form.value.email) {
          form.value.email = "无";
        }
        userAdd(form.value).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }
    if (handleType.value === 2) {
      formRef.value.validate().then((res) => {
        useAppStore.loading = true;
        form.value.sysEmpParam = {
          orgId: form.value.orgId,
          orgName: form.value.orgName,
          posIdList: form.value.posIdList,
          extIds: extIds.value
        };
        if (!form.value.sex) {
          form.value.sex = 3;
        }
        if (!form.value.email) {
          form.value.email = "无";
        }
        userUpdate(form.value).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }
  }
};
function changeOrg(e) {
  form.value.orgName = e;
}

const columns = [
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    customRender: function ({index}) {
      return index + 1;
    },
    width: 80
  },

  {
    title: "账号",
    dataIndex: "account",
    align: "center"
  },

  {
    title: "姓名",
    dataIndex: "name",
    align: "center"
  },

  {
    title: "性别",
    dataIndex: "sex",
    align: "center",
    customRender({text}) {
      if (text === 1) return "男";
      if (text === 2) return "女";
      if (text === 3) return "未知";
      if (text === 0) return "";
    }
  },
  {
    title: "手机",
    dataIndex: "phone",
    align: "center"
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    customRender({text}) {
      let name = "";
      getDicValue("common_status").forEach((item) => {
        if (text == item.code) {
          name = item.name;
        }
      });
      return name;
    }
  },
  {
    title: "操作",
    align: "center",
    width: 180,
    fixed: "right"
  }
];
</script>

<style lang="less" scoped></style>
